package models;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.Domain;

public class DomainModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "domain_";
	
	private static DomainModel instance = null;
	
	public static DomainModel getInstance() {
		if (instance == null) {
			instance = new DomainModel();
		}
		
		return instance;
	}
	
	private DomainModel() {
		try {
			ObjectifyService.register(Domain.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public ArrayList<Domain> list(int page, int limit) {
		ArrayList<Domain> domains = new ArrayList<Domain>();
		
		int start = (page - 1) * limit;
		Query<Domain> q = ofy.query(Domain.class).limit(limit).offset(start);
		for (Domain domain: q) {
			domains.add(domain);
		}
		
		return domains;
	}
	
	public void insert(Domain domain) {
		if (cache != null) {
			cache.put(prefix + domain.getDomain(), domain);
		}
		
		ofy.put(domain);
	}
	
	public void delete(Domain domain) {
		if (cache != null && cache.containsKey(prefix + domain.getDomain())) {
			cache.remove(prefix + domain.getDomain());
		}
		
		ofy.delete(domain);
	}
	
	public Domain getDomain(String name) {
		Domain domain = new Domain();
		if (cache != null && cache.containsKey(prefix + name)) {
			domain = (Domain) cache.get(prefix + name);
		} else {
			try {
				domain = ofy.get(new Key<Domain>(Domain.class, name));
				cache.put(prefix + name, domain);
			} catch (Exception e) {
				domain = null;
			}
		}
		return domain;
	}
}
